package com.wclass.timer;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.wclass.common.DateUtil;
import com.wclass.common.GeTuiUtil;
import com.wclass.entity.*;
import com.wclass.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 定时获取数据
 *
 * @author zhanghaogao
 * @create 2018-09-18 下午12:52
 **/
@Component
@Slf4j
public class HistoryData {

    @Autowired
    private IBaseAppUserService iBaseAppUserService;
    @Autowired
    private ICourseInfoService iCourseInfoService;
    @Autowired
    private ICouresOrderService iCouresOrderService;
    @Autowired
    private IUserAmountBillService iUserAmountBillService;
    @Autowired
    private IUserStatisticsBillService iUserStatisticsBillService;
    @Autowired
    private ICourseClickService iCourseClickService;
    @Autowired
    private IBaseOrganService iBaseOrganService;
    @Autowired
    private ICouresProgressBillService iCouresProgressBillService;
    @Autowired
    private ICourseChapterService iCourseChapterService;

    /**
     * 开课通知
     */
    @Scheduled(cron = "0 28 8-21 * * ? ")
    public void NoticeOfClassOpening() throws Exception {
        EntityWrapper<CourseChapter> chapterEw = new EntityWrapper<>();
        chapterEw.setSqlSelect("course_info_id");
        chapterEw.eq("state", "0").eq("type", "0").gt("start_time", new Date()).lt("start_time", DateUtil.getSomeMinute(new Date(), 30));
        List<Object> chapterList = iCourseChapterService.selectObjs(chapterEw);

        if (chapterList.size() > 0) {
            EntityWrapper<CouresOrder> orderEw = new EntityWrapper<>();
            orderEw.setSqlSelect("pay_person_id");
            orderEw.eq("state", "0").eq("pay_state", "1").in("course_info_id", chapterList);
            List<Object> orderList = iCouresOrderService.selectObjs(orderEw);

            if (orderList.size() > 0) {
                EntityWrapper<BaseAppUser> userEw = new EntityWrapper<>();
                userEw.eq("state", "0").in("id", orderList);
                List<BaseAppUser> userList = iBaseAppUserService.selectList(userEw);

                String cids = "";
                String mobileType = "";
                for (BaseAppUser user : userList) {
                    mobileType = user.getMobileType();
                    if (user.getMobileType() != null && mobileType.equals("android")) {
                        cids += user.getCId() + ",";
                    } else if (user.getMobileType() != null && mobileType.equals("ios")) {
                        cids += user.getDeviceToken() + ",";
                    }
                }
                cids.substring(0, cids.length() - 1);
                String content = "你购买的的课程即将开始，请注意查看。";
                if (cids.split(",").length == 1) {
                    GeTuiUtil.pushMessageToSingle(mobileType, cids, content);
                } else if (cids.split(",").length > 1) {
                    GeTuiUtil.batchPushSingleMessage(cids, content);
                }
            }
        }
    }

    /**
     * 更新用户排行榜
     */
    @Scheduled(cron = "0 0 0/6 * * ?")
    public void userRankingNum() {
        log.debug(" 更新用户排行榜");
        iBaseAppUserService.upRankingNum();
    }

    /**
     * 日更新个人、机构平台推荐状态s
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void updatePlatform(){
        /*
         * 个人平台推荐
         */
        List<BaseAppUser> appUserList = iBaseAppUserService.selectList(new EntityWrapper<BaseAppUser>().eq("platform", 0));
        List<BaseAppUser> appUsers = Lists.newArrayList();
        for (BaseAppUser appUser : appUserList) {
            BaseAppUser user = new BaseAppUser();
            user.setId(appUser.getId());
            /* 平台推荐
             * 拥有5门以上的优质课，且优课率不低于60%
             * 优质课：直播付费课程，课程完成度不低于75%，好评4.5分以上。
             * 完成度=该期次所有直播课到课用户实际上课总时长 ÷ 该期次所有直播课到课用户应上课总时长
             * 优课率=优质课程数 ÷ 课程总数 X 100%
             */
            EntityWrapper<CourseInfo> courseEw = new EntityWrapper<>();
            courseEw.eq("user_id", appUser.getId());
            Integer courseTotalCount = iCourseInfoService.selectCount(courseEw);//课程总数
            courseEw.eq("live_type", 0);
            courseEw.gt("amount", 0);
            courseEw.ge("star", 4.5);
            List<CourseInfo> goodCourseList = iCourseInfoService.selectList(courseEw);
            Integer courseBetterCount = 0;//优质课程数
            for (CourseInfo courseInfo : goodCourseList) {
                //应上课总时长计算
                EntityWrapper<CouresOrder> courseOrderEw = new EntityWrapper<>();
                courseOrderEw.eq("course_info_id", courseInfo.getId());
                courseOrderEw.eq("pay_state", 1);
                Integer orderTotalCount = iCouresOrderService.selectCount(courseOrderEw);//用户课程总下单量
                Integer totalDuration = orderTotalCount * courseInfo.getValidDuration();//应上课总时长

                //实际上课时长
                EntityWrapper<CouresProgressBill> processEw = new EntityWrapper<>();
                processEw.eq("course_info_id", courseInfo.getId());
                List<CouresProgressBill> processList = iCouresProgressBillService.selectList(processEw);
                int actDuration = 0;
                for (CouresProgressBill couresProgressBill : processList) {
                    actDuration += couresProgressBill.getStudyDuration();
                }
                int finishDegree = 0;
                if (totalDuration != 0)
                    finishDegree = new BigDecimal(actDuration).divide(new BigDecimal(totalDuration), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).intValue();
                if (finishDegree > 75)
                    ++courseBetterCount;
            }
            int betterDegree = 0;
            if (courseTotalCount != 0)
                betterDegree = new BigDecimal(courseBetterCount).divide(new BigDecimal(courseTotalCount)).multiply(new BigDecimal(100)).intValue();
            if (courseBetterCount >= 5 && betterDegree > 60)
                user.setPlatform(1);
            else
                user.setPlatform(0);
            appUsers.add(user);
        }
        if (appUsers.size() > 0)
            iBaseAppUserService.updateBatchById(appUsers);

        /*
         * 机构平台推荐
         */
        List<BaseOrgan> organList = iBaseOrganService.selectList(new EntityWrapper<BaseOrgan>().eq("platform", 0));
        List<BaseOrgan> organs = Lists.newArrayList();
        for (BaseOrgan baseOrgan : organList) {
            BaseOrgan organ = new BaseOrgan();
            organ.setId(baseOrgan.getId());

            EntityWrapper<CourseInfo> courseEw = new EntityWrapper<>();
            courseEw.eq("crt_user_id", organ.getUserId());
            Integer courseTotalCount = iCourseInfoService.selectCount(courseEw);//课程总数
            courseEw.eq("live_type", 0);
            courseEw.gt("amount", 0);
            courseEw.ge("star", 4.5);
            List<CourseInfo> goodCourseList = iCourseInfoService.selectList(courseEw);
            Integer courseBetterCount = 0;//优质课程数
            for (CourseInfo courseInfo : goodCourseList) {
                //应上课总时长计算
                EntityWrapper<CouresOrder> courseOrderEw = new EntityWrapper<>();
                courseOrderEw.eq("course_info_id", courseInfo.getId());
                courseOrderEw.eq("pay_state", 1);
                Integer orderTotalCount = iCouresOrderService.selectCount(courseOrderEw);//用户课程总下单量
                Integer totalDuration = orderTotalCount * courseInfo.getValidDuration();//应上课总时长

                //实际上课时长
                EntityWrapper<CouresProgressBill> processEw = new EntityWrapper<>();
                processEw.eq("course_info_id", courseInfo.getId());
                List<CouresProgressBill> processList = iCouresProgressBillService.selectList(processEw);
                int actDuration = 0;
                for (CouresProgressBill couresProgressBill : processList) {
                    actDuration += couresProgressBill.getStudyDuration();
                }
                int finishDegree = 0;
                if (totalDuration != 0)
                    finishDegree = new BigDecimal(actDuration).divide(new BigDecimal(totalDuration), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).intValue();
                if (finishDegree > 75)
                    ++courseBetterCount;
            }
            int betterDegree = 0;
            if (courseTotalCount != 0)
                betterDegree = new BigDecimal(courseBetterCount).divide(new BigDecimal(courseTotalCount)).multiply(new BigDecimal(100)).intValue();
            if (courseBetterCount >= 5 && betterDegree > 60)
                organ.setPlatform(1);
            else
                organ.setPlatform(0);
            organs.add(organ);
        }
        if (organs.size() > 0)
            iBaseOrganService.updateBatchById(organs);
    }

    /**
     * 用户日数据统计
     */
    @Scheduled(cron = "0 30 0 * * ?")
    public void userStatisticsDay() {
        Date stDate = DateUtil.getSomeDay(DateUtil.getStartTime(new Date()), -1);
        Date endDate = DateUtil.getSomeDay(DateUtil.getEndTime(new Date()), -1);
        log.debug("更新用户日统计");
        for (int i = 0; i < i + 1; i++) {
            Page<BaseAppUser> obj = iBaseAppUserService.selectPage(new Page<>(i + 1, 10), new EntityWrapper<>());
            if (obj.getRecords() == null || obj.getRecords().size() == 0) {
                break;
            }
            List<Object> ids = iCourseInfoService.selectObjs(new EntityWrapper<CourseInfo>().eq("user_id",
                    obj.getRecords().get(i).getId()).setSqlSelect("id"));
            //点击数
            Integer clickNum = iCourseClickService.selectCount(new EntityWrapper<CourseClick>().in(
                    "course_info_id", ids).ge("crt_time", stDate).le("crt_time", endDate));
            //成单数
            Integer orderNum = iCouresOrderService.selectCount(new EntityWrapper<CouresOrder>().in(
                    "course_info_id", ids).ge("pay_time", stDate).le("pay_time", endDate).eq("pay_state", 1));
            //获取成单金额
            Long orderAmount = (long) iUserAmountBillService.selectObj(new EntityWrapper<UserAmountBill>().eq(
                    "user_id", obj.getRecords().get(i).getId()).ge("crt_time", stDate).le("crt_time", endDate).eq(
                    "source_type", 0).setSqlSelect("SUM(amount)"));
            iUserStatisticsBillService.insert(new UserStatisticsBill(obj.getRecords().get(i).getId(), clickNum,
                    orderNum, orderAmount, 0));
            //周一统计
            if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == 2) {
                //数据周统计
                Date stWeekDate = DateUtil.getSomeDay(stDate, -6);
                //点击数
                clickNum = iCourseClickService.selectCount(new EntityWrapper<CourseClick>().in(
                        "course_info_id", ids).ge("crt_time", stWeekDate).le("crt_time", endDate));
                //成单数
                orderNum = iCouresOrderService.selectCount(new EntityWrapper<CouresOrder>().in(
                        "course_info_id", ids).ge("pay_time", stWeekDate).le("pay_time", endDate).eq("pay_state", 1));
                //获取成单金额
                orderAmount = (long) iUserAmountBillService.selectObj(new EntityWrapper<UserAmountBill>().eq(
                        "user_id", obj.getRecords().get(i).getId()).ge("crt_time", stWeekDate).le("crt_time",
                        endDate).eq("source_type", 0).setSqlSelect("SUM(amount)"));
                iUserStatisticsBillService.insert(new UserStatisticsBill(obj.getRecords().get(i).getId(), clickNum,
                        orderNum, orderAmount, 1));

            }
            //月统计
            if (Calendar.getInstance().get(Calendar.DATE) == 1) {
                //数据周统计
                Date stMonthDate = DateUtil.getMonthStartTime(stDate);
                //点击数
                clickNum = iCourseClickService.selectCount(new EntityWrapper<CourseClick>().in(
                        "course_info_id", ids).ge("crt_time", stMonthDate).le("crt_time", endDate));
                //成单数
                orderNum = iCouresOrderService.selectCount(new EntityWrapper<CouresOrder>().in(
                        "course_info_id", ids).ge("pay_time", stMonthDate).le("pay_time", endDate).eq("pay_state", 1));
                //获取成单金额
                orderAmount = (long) iUserAmountBillService.selectObj(new EntityWrapper<UserAmountBill>().eq(
                        "user_id", obj.getRecords().get(i).getId()).ge("crt_time", stMonthDate).le("crt_time",
                        endDate).eq("source_type", 0).setSqlSelect("SUM(amount)"));
                iUserStatisticsBillService.insert(new UserStatisticsBill(obj.getRecords().get(i).getId(), clickNum,
                        orderNum, orderAmount, 2));

            }
        }
        log.debug("用户日统计完成");
        //清空60天月前的统计数据
        iUserStatisticsBillService.delete(new EntityWrapper<UserStatisticsBill>().ne("type", 2).le("crt_time",
                DateUtil.getSomeDay(new Date(), -60)));
        //清空60天前的点击记录
        iCourseClickService.delete(new EntityWrapper<CourseClick>().le("crt_time",
                DateUtil.getSomeDay(new Date(), -60)));
    }


}
